/* eslint-disable */
// iOS11手机HLS直播在m3u8响应时间过长后不继续请求的hack
function ios11Hack (video) {
  var isloadeddata = false
  var isPlaying = false
  var stalledCount = 0
  video.addEventListener('loadeddata', function () {
    isloadeddata = true
  }, false)
  video.addEventListener('stalled', function () {
    stalledCount ++
    if (!isPlaying) {
      if (stalledCount >= 2 && !isloadeddata) {
        video.load()
        video.play()
        isloadeddata = false
        isPlaying = false
        stalledCount = 0
      }
    }
  }, false)
  video.addEventListener('playing', function () {
    isPlaying = true
  })
}

Date.prototype.Format = function (fmt) { // author: meizz
  var o = {
    'M+': this.getMonth() + 1, // 月份
    'd+': this.getDate(), // 日
    'h+': this.getHours(), // 小时
    'm+': this.getMinutes(), // 分
    's+': this.getSeconds(), // 秒
    'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
    'S': this.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length))
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      return fmt
    }
  }
}

var Domain = 'https://open.ys7.com'
var ckplayerJS = Domain + '/sdk/js/1.3/ckplayer/ckplayer.js'
var ckplayerSWF = Domain + '/sdk/js/1.3/ckplayer/ckplayer.swf'
var m3u8SWF = Domain + '/sdk/js/1.3/ckplayer/m3u8.swf'
var hlsJS = Domain + '/sdk/js/1.3/hls.min.js'

// 当前页面是否是https协议
var isHttps = location.protocol === 'https:' ? true : false
// 是否为移动端
var isMobile = !!navigator.userAgent.match(/(iPhone|iPod|iPad|Android|ios|SymbianOS)/i)
var testVideo = document.createElement('video')
// 是否支持video标签和addEventListener方法（主要为了区别ie8）
var isModernBrowser = !!testVideo.canPlayType && !!window.addEventListener
// 是否能使用video原生播放hls
var isNativeSupportHls = isModernBrowser && testVideo.canPlayType('application/vnd.apple.mpegURL')
// 是否能使用hls.js播放
var isSupportHls = false
// 是否使用flash
var useFlash = false

// 本地信息上报
// var LOCALINFO = 'open_netstream_localinfo'
// 预览主表上报
// var PLAY_MAIN = 'open_netstream_play_main'

var RTMP_REG = /^rtmp/
var HLS_REG = /\.m3u8/

// 获取元素样式
function getStyle(el) {
  return window.getComputedStyle
    ? window.getComputedStyle(el, null)
    : el.currentStyle
}

/**
 * [addJs 异步添加js]
 * @param {String}   filename [文件CDN]
 * @param {Function} callback [cb]
 */
function addJs(filename, callback) {
  var oJs = document.createElement('script')
  oJs.setAttribute('src', filename)
  oJs.onload = callback
  document.getElementsByTagName('head')[0].appendChild(oJs)
}

var idLoadHandler = false;

function loadHandler() {
  idLoadHandler = true;
}

const EZUIPlayer = function (videoId) {
  if (!isModernBrowser) {
    throw new Error('不支持ie8等低版本浏览器')
    return
  }
  if (typeof videoId !== 'string') {
    throw new Error('EZUIPlayer requires parameter videoId')
  }
  this.videoId = videoId;
  this.video = document.getElementById(videoId)
  if (!this.video) {
    throw new Error('EZUIPlayer requires parameter videoId')
  }
  this.opt = {}
  this.opt.sources = []
  var sources = this.video.getElementsByTagName('source')
  // 转为数组对象，不受removeChild影响
  sources = Array.prototype.slice.call(sources, 0)

  // 如果视频源地址直接写在video的情况
  if (this.video.src) {
    // 移动端删除rtmp地址
    if (isMobile && RTMP_REG.test(this.video.src)) {
      // FIXED
      // this.video.removeAttribute('src')
      // this.video.load()
    } else {
      this.opt.sources.push(this.video.src)
    }
  }
  let l = sources.length;
  if (l > 0) {
    for (var i = 0; i < l; i++) {
      // 移动端删除rtmp地址
      if (isMobile && RTMP_REG.test(sources[i].src)) {
        this.video.removeChild(sources[i])
      } else {
        this.opt.sources.push(sources[i].src)
      }
    }
  }

  if (this.opt.sources.length < 1) {
    throw new Error('no source found in video tag.')
  }
  // 当前播放源的下标
  this.opt.cur = 0
  // 事件存储
  this.handlers = {}

  this.opt.poster = this.video.poster
  var videoStyle = getStyle(this.video)
  var width = this.video.width
  var height = this.video.height
  if (width) {
    this.opt.width = width
    if (height) {
      this.opt.height = height
    } else {
      this.opt.height = 'auto'
    }
    // this.log('video width:' + this.opt.width + ' height:' + this.opt.height);
  } else {
    this.opt.width = videoStyle.width
    this.opt.height = videoStyle.height
    // this.log('videoStyle.width:' + videoStyle.width + ' wideoStyle.height:' + videoStyle.height);
  }
  this.opt.parentId = videoId;
  this.opt.autoplay = this.video.autoplay ? true : false
  // this.log('autoplay:' + this.video.autoplay);
  // 尝试播放
  this.tryPlay()
  this.initTime = (new Date()).getTime()

  // this.retry = 2
}

// 事件监听
EZUIPlayer.prototype.on = function(eventName, callback) {
  if (typeof eventName !== 'string' || typeof callback !== 'function') {
    return
  }
  if (typeof this.handlers[eventName] === 'undefined') {
    this.handlers[eventName] = []
  }
  this.handlers[eventName].push(callback);
}

  // 事件触发
EZUIPlayer.prototype.emit = function () {
  if (this.handlers[arguments[0]] instanceof Array) {
    const handlers = this.handlers[arguments[0]]
    const l = handlers.length
    for (let i = 0; i < l; i++) {
      handlers[i].apply(this, Array.prototype.slice.call(arguments, 1))
    }
  }
}

// 尝试播放
EZUIPlayer.prototype.tryPlay = function () {
  this.opt.currentSource = this.opt.sources[this.opt.cur]
  if (!this.opt.currentSource) {
    // this.log('未找到合适的播放URL')
    return
  }
  const me = this
  // 如果是HLS地址
  // 移动端使用.m3u8播放
  // 如果是rtmp格式使用手机时, 把播放视频源轨道+1递归
  if (/\.m3u8/.test(this.opt.currentSource)) {
    // 如果是手机浏览器环境,或者原生支持HLS播放的,直接使用video标签播放
    // 否则尝试使用hls.js播放，
    // 最后使用flash
    if (isMobile || isNativeSupportHls) {
      // this.log('使用原生video')
      this.video.style.heght = this.opt.height = Number(this.opt.width.replace(/px$/g, '')) * 9 / 16 + 'px'
      // 初始化video播放
      this.initVideoEvent()
    } else {
      if (isHttps) {
        addJs(ckplayerJS, function () {
          me.initCKPlayer();
        })
      } else {
        addJs(hlsJS, function () {
          isSupportHls = Hls.isSupported()
          if (isSupportHls) {
            // me.log('使用hls.js')
            me.initHLS()
          } else {
            useFlash = true
            // me.log('2 使用flash');
            addJs(ckplayerJS, function () {
              me.initCKPlayer()
            })
          }
        })
      }
    }
  } else if (/^rtmp:/.test(this.opt.currentSource)) {
    if (isMobile) {
      this.opt.cur++
      this.tryPlay()
      return
    } else {
      addJs(ckplayerJS, function () {
        me.initCKPlayer()
      })
    }
  }
}

// 初始化hls.js
EZUIPlayer.prototype.initHLS = function () {
  const me = this
  const hls = new Hls({defaultAudioCodec: 'mp4a.40.2'}) // 萤石设备默认使用 AAC LC 音频编码
  hls.loadSource(this.opt.currentSource)
  hls.attachMedia(this.video)
  hls.on(Hls.Events.MANIFEST_PARSED, function () {
    if (me.opt.autoplay) {
      me.video.play()
    }
    me.initVideoEvent()
  })
  hls.on(Hls.Events.ERROR, function (event, data) {
    if (data.fatal) {
      switch(data.type) {
        case Hls.ErrorTypes.NETWORK_ERROR:
          // try to recover network error
          console.log('fatal network error encountered, try to recover')
          hls.startLoad()
          break
        case Hls.ErrorTypes.MEDIA_ERROR:
          console.log('fatal media error encountered, try to recover')
          hls.recoverMediaError()
          break
        default:
          // cannot recover
          hls.destroy()
          break
      }
    }
  })

  this.hls = hls;
}

// 初始化ckplayer
EZUIPlayer.prototype.initCKPlayer = function () {
  // this.log('ckplayer初始化')
  const me = this

  // 新增相同id的div标签，然后删除video标签
  this.videoFlash = document.createElement('DIV')
  this.video.parentNode.replaceChild(this.videoFlash, this.video)
  this.video = this.videoFlash
  this.videoFlash.id = this.opt.parentId
  let flashvars = null
  // 如果rtmp服务器环境设置了视频暂停则断开链接
  // 需要修改ckplayer.js  setup参数第30个值
  // 在播放暂停后点击播放是否采用重新链接的方式
  if (/^rtmp/.test(this.opt.currentSource)) {
    flashvars = {
      f: this.opt.currentSource,
      c: 0,
      p: this.opt.autoplay ? 1 : 0,
      i: this.opt.poster,
      lv: 1,
      loaded: 'loadHandler',
      wh: '16:9'
    }
  } else if (/\.m3u8/.test(this.opt.currentSource)) {
    flashvars = {
      s: 4,  // 4-使用swf视频流插件播放
      f:m3u8SWF,
      a: this.opt.currentSource,
      c: 0,  // 0-使用ckplayer.js的配置 1-使用ckplayer.xml的配置
      lv:1, // 1-直播 0-普通方式
      p: this.opt.autoplay ? 1 : 0,   // 1-默认播放 0-默认暂停
      i: this.opt.poster,
      loaded: 'loadHandler',
      wh: '16:9'
    }
  } else {
    flashvars = {
      f: this.opt.currentSource,
      c: 0,
      p: 1,
      loaded: 'loadHandler',
      wh: '16:9'
    }
  }
  var params = {
    bgcolor: '#FFF',
    allowFullScreen: true,
    allowScriptAccess: 'always',
    wmode:'transparent'
  }
  this.flashId = this.opt.parentId + 'flashId'
  CKobject.embedSWF(ckplayerSWF, this.opt.parentId, this.flashId, this.opt.width, this.opt.height, flashvars, params)
}

EZUIPlayer.prototype.initVideoEvent = function () {
  ios11Hack(this.video)
}

// @see http://www.ckplayer.com/manual/13/52.htm
EZUIPlayer.prototype.play = function () {
  this.opt.autoplay = true;
  if (!!window['CKobject']) {
    if (idLoadHandler) {
      CKobject.getObjectById(this.flashId).videoPlay()
    }
  } else if (!!this.video) {
    this.video.play()
  }
}

EZUIPlayer.prototype.pause = function () {
  this.opt.autoplay = false
  if (!!window['CKobject'] && idLoadHandler) {
    if (idLoadHandler) {
      CKobject.getObjectById(this.flashId).videoPause()
    }
  } else if (!!this.video) {
    this.video.pause()
  }
}

EZUIPlayer.prototype.load = function () {
  if (!!window['CKobject']) {
    // flash load
  } else if (!!this.video) {
    this.video.load()
  }
}
//
// EZUIPlayer.prototype.remove = function () {
//
// };
//
// EZUIPlayer.prototype.clear = function () {
//
// };

// 切换视频源
EZUIPlayer.prototype.changeSource = function (source) {
  this.opt.currentSource = source
  this.initCKPlayer()
}

export default EZUIPlayer
